package kuang;

/**
 * @author cyt
 * @create 2020-03-08 22:09
 */

/**
 * 模拟, 演员和观众。 通过标志位来实现。
 * <p>
 * 需要：演员， Tv, 观众
 */
public class Thread_Process_two {
    public static void main(String[] args) {
        TV tv = new TV();
        new Play(tv).start();
        new Wather(tv).start();

    }
}
class Play extends Thread {
    TV tv;

    public Play(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                try {
                    tv.playvoice("表演了猫和老鼠");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    tv.playvoice("广告");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Wather extends Thread {
    TV tv;
    public Wather(TV tv) {
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                tv.watchvoice();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class TV {

    // 演员表演， 观众等待 T
    // 演员等待， 观众表演 F
    // 节目、 标志位
    boolean flag = true;
    String voice;
    // 表演方法
    public synchronized void playvoice(String voice) throws InterruptedException {
        if (!flag) {
            this.wait();
        }
        System.out.println("演员表演了：" + voice);

        this.notify(); // 通知观看
        this.voice = voice;
        this.flag = !this.flag;
    }

    // 观看方法
    public synchronized void watchvoice() throws InterruptedException {
        if (flag) {
            this.wait();
        }
        System.out.println("观看了：" + voice);
        this.notify();
        this.flag = !this.flag;
    }
}
